json_minimal
A minimal json crate conforming to https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf .
Tutorial (creating jsons)
In order to create a valid (i.e. generally accepted) json you should always start with:
use *;
let mut json = new;
// which is equivalent to
let mut json = JSON;
// ...
To add an object, simply do this:
// ...
let greeting =
OBJECT
;
json.add;
// ...
or alternatively:
// ...
json.add;
// ...
As you can see, whilst the crate is minimal (in my opinion) it may not be the quickest to work with. This becomes clearer when adding an array to an object:
// ...
let mut days_in_the_week =
OBJECT
;
let mut days = ARRAY;
days
.add
.add
.add
.add
.add
.add
.add
;
days_in_the_week
.add
.add
;
json.add;
// ...
In conclusion:
// ...
let mut conclusion =
OBJECT
;
conclusion
.add
.add
.add
;
json.add;
// ...
Calling:
// ...
let resulting_json = json.print;
will result in a String
containing:
{"Greeting":"Hello, world!","Days of the week":{"Total number of days":7,"They are called":["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]},"Conclusion":{"Minimal in my opinion":true,"How much I care about your opinion":null,"Comment":";)"}}
If you would like the json string in a different format you can easily make your own 'print' function.
Tutorial (parsing and working with jsons)
Parsing a json value from bytes is even more minimal - at the cost of being more cumbersome. Let's see how we can parse the json we generated above:
use *;
let json = match parse
// ...
Let's first talk about what information is given for a parsing error. As you might expect it is minimal. position
above is the position were everything went wrong and the message
will be something like"Error parsing array."
if, for example, a closing ]
is missing somewhere. Continuing where we left off:
// ...
match json.get
// ...
Unfortunately all of this was necessary because, even though we were able to confirm that "Greeting"
exists, we had no way of knowing what it really is. It's not over:
// ...
match json.get
// You get the idea.
The function Json::parse(...)
can also parse 'standalone values'. Example:
match parse
// Another example:
match parse
Changes & Improvements
-
Lonami (github) has made improvements:
json_minimal
can now parse non-ASCII strings and escape sequences. (I overlooked this, I admit.)- The code is cleaner thanks to the question-mark operator and using rustfmt.
- Some parsing stuff that didn't work now works.
A thousand thanks to Lonami !!!
-
json_minimal
can now also parse 'pretty' json like this (as long as only\r
,\n
,\t
and whitespace were used for formatting):
{
"Array": [ "Hello" , "World" , "!" ]
}
This should also have worked from the start but I did not include because it of my aversion to energy inefficiency (although it is, perhaps, unfounded).
Please let me know if something doesn't work. I can't promise i'll react immediately, though.